import { PlusOutlined, ExclamationCircleFilled } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import { Button, Switch, message, Card, Popconfirm, Modal } from 'antd';
import { useRef, useState,useEffect } from 'react';
import { getMemberList, postMemberDelete, postMemberResetPwd, postMemberStatus ,getdownload} from './request';
import FormModal from './components/FormModel';
import copy from 'copy-to-clipboard';
import { useIntl } from '@umijs/max';
export const waitTimePromise = async (time: number = 100) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(true);
    }, time);
  });
};

export const waitTime = async (time: number = 100) => {
  await waitTimePromise(time);
};

// 定义columns的属性类型
type GithubIssueItem = {
  isSuper: boolean | undefined;
  id: number;
  hid: number;
  realName: string;
  username: string;
  passwordHash: string;
  salt: string;
  passwordResetToken: string;
  avatar: string;
  sex: number;
  mobile: string;
  permissionStrings: string;
  lastActiveAt: string;
  remark: string;
  status: number;
  createdAt: string;
  updatedAt: string;
  deptName: string;
  roleName: string;
};

const Administrator = () => {
  // 表格ref
  const actionRef = useRef<ActionType | null>(null);

  // 表单对话框显示
  const [modalShow, setModalShow] = useState<boolean>(false);

  // 操作的用户id
  const [id, setId] = useState(0);

  // 操作的用户信息
  const [info, setInfo] = useState<GithubIssueItem | null>(null);

  // 获取对话框中的确认弹框 emergency_soft
  const { confirm } = Modal;

  const intl = useIntl();

  // 切换用户状态
  const handleCheck = async (record: GithubIssueItem): Promise<void> => {
    const res: any = await postMemberStatus({
      status: record.status === 1 ? 2 : 1,
      id: record.id,
    });
    if (res.code !== 0) {
      message.error(res.msg);
      return;
    }
    message.success(res.msg);
    actionRef.current?.reload();
  };
  // 操作选项
  const handleEdit = (key: null | string, record: GithubIssueItem) => {
    setId(record.id);
    setInfo(record);
    setModalShow(true);
  };

  const confirmDel = async (e: any, record: GithubIssueItem) => {
    const res: any = await postMemberDelete(record.id);
    if (res.code !== 0) {
      message.error(res.msg);
      return;
    }
    message.success(intl.formatMessage({ id: 'SetUser.deleted' }));
    actionRef.current?.reload();
  };

  function getRandomString(len = 12, isSmall = false) {
    const _charStr = 'abacdefghjklmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789';
    const _smallCharStr = 'abacdefghjklmnopqrstuvwxyz0123456789';
    const charStr = isSmall ? _smallCharStr : _charStr;
    const min = 0;
    const max = charStr.length - 1;
    let _str = ''; //循环生成字符串
    for (let i = 0, index; i < len; i++) {
      index = (function (randomIndexFunc, i) {
        return randomIndexFunc(min, max, i, randomIndexFunc);
      })(function (
        min: number,
        max: number,
        i: number,
        _self: (arg0: any, arg1: any, arg2: any, arg3: any) => number,
      ) {
        const numStart = _charStr.length - 10;
        let indexTemp = Math.floor(Math.random() * (max - min + 1) + min);
        if (i === 0 && indexTemp >= numStart) {
          indexTemp = _self(min, max, i, _self);
        }
        return indexTemp;
      }, i);
      _str += _charStr[index];
    }
    return _str;
  }

  const confirmReset = async (random: string, record: GithubIssueItem) => {
    console.log('修改密码为：', random);
    const res: any = await postMemberResetPwd({ id: record.id, password: random });
    if (res.code !== 0) {
      message.error(res.msg);
      return;
    }
    message.success(intl.formatMessage({ id: 'SetUser.reset' }));
    actionRef.current?.reload();
  };

  const copyText = async (value: string) => {
    const res = copy(value, {
      debug: true,
      message: intl.formatMessage({ id: 'SetUser.Copied' }),
    });
    if (res) {
      message.success(intl.formatMessage({ id: 'SetUser.Copied' }),);
    } else {
      message.error(intl.formatMessage({ id: 'SetUser.copy Error' }));
    }
  };

  const resetPwd = (record: GithubIssueItem) => {
    const random = getRandomString();

    confirm({
      title: intl.formatMessage({ id: 'SetUser.reset user' }),
      icon: <ExclamationCircleFilled />,
      content: (
        <a
          onClick={() => {
            copyText(random);
          }}
        >
          {intl.formatMessage({ id: 'SetUser.Copy password' })}
        </a>
      ),
      onOk() {
        confirmReset(random, record);
      },
      onCancel() {},
    });
  };

  // 表格列配置
  const columns: ProColumns<GithubIssueItem>[] = [
    {
      title: intl.formatMessage({ id: 'SetUser.serial' }),
      dataIndex: 'inedx',
      valueType: 'index',
      width: 70,
    },
    {
      title: intl.formatMessage({ id: 'SetUser.Username' }),
      dataIndex: 'username',
      // copyable: true,
      ellipsis: true,
    },
    {
      title: intl.formatMessage({ id: 'SetUser.Mobile' }),
      dataIndex: 'mobile',
      ellipsis: true,
    },
    {
      title: intl.formatMessage({ id: 'SetUser.Real Name' }),
      dataIndex: 'realName',
      ellipsis: true,
      search: false,
    },
    {
      title:intl.formatMessage({ id: 'SetUser.Number of logins' }),
      dataIndex: 'deptName',
      ellipsis: true,
      search: false,
    },
    {
      title: intl.formatMessage({ id: 'SetUser.Last login IP' }),
      dataIndex: 'roleName',
      ellipsis: true,
      search: false,
    },
    {
      title: intl.formatMessage({ id: 'SetUser.Last login time' }),
      dataIndex: 'postIds',
      ellipsis: true,
      search: false,
    },
    {
      title: intl.formatMessage({ id: 'SetUser.status' }),
      dataIndex: 'status',
      ellipsis: true,
      search: false,
      render: (text, record) => {
        let word = false; // 默认性别
        if (record.status === 1) {
          word = true;
        } else if (record.status === 0) {
          word = false;
        }
        return (
          <Switch
            checkedChildren={intl.formatMessage({ id: 'SetUser.Available' })}
            unCheckedChildren={intl.formatMessage({ id: 'SetUser.Disabled' })}
            defaultChecked={word}
            onChange={() => handleCheck(record)}
            disabled={record.isSuper}
          />
        );
      },
    },
    {
      title: intl.formatMessage({ id: 'SetUser.Remark' }),
      dataIndex: 'remark',
      ellipsis: true,
      search: false,
    },

    {
      title: intl.formatMessage({ id: 'SetUser.Action' }),
      valueType: 'option',
      key: 'option',
      width: 240,
      align: 'center',
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      render: (_text: any, record: GithubIssueItem, _: any, _action: any) => [
        <Button
          key="update"
          type="link"
          onClick={() => handleEdit('update', record)}
          disabled={record.isSuper}
        >
          {intl.formatMessage({ id: 'SetUser.Edit' })}
        </Button>,
        <Button key="reset" type="link" onClick={() => resetPwd(record)} disabled={record.isSuper}>
          {intl.formatMessage({ id: 'SetUser.Reset' })}
        </Button>,
        <Popconfirm
          key="delete"
          title={intl.formatMessage({ id: 'SetUser.Dle user' })}
          description=""
          onConfirm={(e) => confirmDel(e, record)}
          okText={intl.formatMessage({ id: 'SetUser.OK' })}
          cancelText={intl.formatMessage({ id: 'SetUser.cancel' })}
          disabled={record.isSuper}
        >
          <Button type="link" disabled={record.isSuper}>
            {intl.formatMessage({ id: 'SetUser.Delete' })}
          </Button>
        </Popconfirm>,
      ],
    },
  ];

  return (
    <>
      <Card>
        <ProTable<GithubIssueItem>
          defaultSize={'large'}
          columns={columns}
          actionRef={actionRef}
          cardBordered
          request={async (params) => {
            await waitTime(500);
            const res: any = await getMemberList({
              page: params.current,
              pageSize: params.pageSize,
              username: params.username ? params.username : '',
              mobile: params.mobile ? params.mobile : '',
            });
            return {
              data: res.data.list ? res.data.list : [],
              success: res.code === 0 ? true : false,
              total: res.data.totalCount,
            };
          }}
          editable={{
            type: 'multiple',
          }}
          columnsState={{
            persistenceKey: 'pro-table-singe-demos',
            persistenceType: 'localStorage',
          }}
          rowKey="id"
          search={{
            labelWidth: 'auto',
          }}
          options={{
            setting: {
              listsHeight: 400,
            },
          }}
          form={{
            // 由于配置了 transform，提交的参与与定义的不同这里需要转化一下
            syncToUrl: (values, type) => {
              if (type === 'get') {
                return {
                  ...values,
                };
              }
              return values;
            },
          }}
          pagination={{
            defaultPageSize: 10,
            showSizeChanger: true,
          }}
          dateFormatter="string"
          headerTitle={intl.formatMessage({ id: 'SetUser.User List' })}
          toolBarRender={() => [
            <Button
              key="button"
              icon={<PlusOutlined />}
              onClick={() => {
                setModalShow(true);
              }}
              type="primary"
            >
             {intl.formatMessage({ id: 'SetUser.New User' })}
            </Button>,
          ]}
        />
      </Card>
      <FormModal
        visible={modalShow}
        info={info}
        id={id}
        onCancel={() => {
          setModalShow(false);
          setId(0);
        }}
        done={() => actionRef.current?.reload()}
      />
    </>
  );
};

export default Administrator;
